package com.zzyl.nursing.service.impl;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.constants.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author zjf
 * @date 2025-06-10
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }



    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo  selectDeviceDataList(DeviceDataPageReqDto dto) {
        //分页对象
        Page<DeviceData> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        //查询条件
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        //查询某个设备的某个物模型的某个范围的多条数据，并且分页展示
        //设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
            queryWrapper.eq(DeviceData::getDeviceName, dto.getDeviceName());
        }
        //物模型
        if(StringUtils.isNotEmpty(dto.getFunctionId())){
            queryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        //时间范围
        if(ObjectUtil.isNotEmpty(dto.getStartTime())&&ObjectUtil.isNotEmpty(dto.getEndTime())){
            queryWrapper.between(DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());
        }

        //分页查询
        page = page(page, queryWrapper);

        return getTableDataInfo(page);
    }


    private static TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量保存数据
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
//        LambdaQueryWrapper.eq(Device::getIotId,deviceId);
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device == null){
            return;
        }
        //获取设备上报的数据，一个设备可以用多个service
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            //获取设备上报的数据，一个service可以有多个property
            Map<String, Object> properties = service.getProperties();
            if (ObjectUtil.isEmpty(properties)){
                return;
            }
            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //设备的物模型数据
            List<DeviceData> deviceDataList = new ArrayList<>();
            properties.forEach((k,v)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .deviceName(device.getDeviceName())
                        .functionId(k)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(v+"")
                        .alarmTime(alarmTime)
                        .build();
                deviceDataList.add(deviceData);

            });
            //批量保存
            saveBatch(deviceDataList);
            //保存到redis中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr( deviceDataList));

        });

    }
}
